//
//  LoginViewController.m
//  Calculated
//
//  Created by 张庆勇 on 2018/3/21.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "LCAFRequestHost.h"
#import "LCAFCache.h"
@interface LCAFRequestHost()
@property (nonatomic,strong) LCAFCache *afCache;
@end
@implementation LCAFRequestHost
DEFINE_SINGLETON_FOR_CLASS(LCAFRequestHost)
- (id)init
{
    self = [super init];
    if (self) {
    
        self.baseUrlStr = [NSString stringWithFormat:@"%@", HOST_IP];
        NSURL *baseUrl = [NSURL URLWithString:self.baseUrlStr];
        self.requestManager = [[AFHTTPSessionManager alloc]initWithBaseURL:baseUrl];
        self.requestManager.operationQueue.maxConcurrentOperationCount = MaxOperationCount;
        self.afCache = [[LCAFCache alloc]initWithDirectoryName:kAFCacheDirectoryName
                                                    memoryCost:kAFMemoryCost];
        
        
        self.requestManager.responseSerializer = [AFJSONResponseSerializer serializer];
        AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
        response.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
        response.removesKeysWithNullValues = YES;
        self.requestManager.responseSerializer = response;
        self.requestManager.requestSerializer.timeoutInterval = TimeOut;
    }
    return self;
}
//- (AFSecurityPolicy *)customSecurityPolicy
//{
//    // https ssl 验证函数 + (AFSecurityPolicy *)customSecurityPolicy {
//    // 先导入证书 证书由服务端生成，具体由服务端人员操作
//    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"zg.com" ofType:@"cer"];//证书的路径
//    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
//    
//    // AFSSLPinningModeCertificate 使用证书验证模式
//    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
//    // 如果是需要验证自建证书，需要设置为YES
//    securityPolicy.allowInvalidCertificates = NO;
//    
//    //validatesDomainName 是否需要验证域名，默认为YES;
//    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
//    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
//    //如置为NO，建议自己添加对应域名的校验逻辑。
//    securityPolicy.validatesDomainName = YES;
//    
//    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil];
//    
//    return securityPolicy;
//
//}
- (void)enableCacheWithDirectory:(NSString *)cacheDirectoryPath
                    inMemoryCost:(NSUInteger)inMemoryCost
{
    self.afCache = nil;
    self.afCache = [[LCAFCache alloc]initWithDirectoryName:cacheDirectoryPath
                                                memoryCost:inMemoryCost];
}
- (void)afRequestWithUrlString:(NSString *)urlString
                        method:(NSString *)method
                    parameters:(NSDictionary *)param
                         cache:(BOOL)isCache
                  successBlock:(LCSuccessBlock)success
                     failBlock:(LCFailBlock)fail
{
    
    if (![urlString isEqualToString: @"site"] && ![urlString isEqualToString:upgrade]) {
        
        [ self.requestManager.requestSerializer setValue:[NSString stringWithFormat:@"%@",[AppDelegate shareAppdelegate].sizeId] forHTTPHeaderField:@"X-SITE-ID"];
        
    }else
    {
        [self.requestManager.requestSerializer setValue:nil forHTTPHeaderField:@"Host"];
    }
    if ( [EXUserManager isLogin]) {
        NSString *token = [NSString stringWithFormat:@"Bearer %@",[EXUserManager userInfo].token];
        [ self.requestManager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];

    }else
    {
        if ([urlString isEqualToString:userSMS] || [urlString isEqualToString:safeLogin]) {
            NSString *token = [NSString stringWithFormat:@"Bearer %@",[EXUserManager userInfo].token];
            [ self.requestManager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
        }else
        {
            [self.requestManager.requestSerializer setValue:nil forHTTPHeaderField:@"Authorization"];
        }
    }
    NSString *languageCode = [ZBLocalized sharedInstance].currentLanguage;
    if([languageCode hasPrefix:@"zh-Hant"]){
        languageCode = @"zh-hant";//繁体中文
    }else if([languageCode hasPrefix:@"zh-Hans"]){
        languageCode = @"zh-hans";//简体中文
    }else if([languageCode hasPrefix:@"ja"]){
        languageCode = @"ja";//日语
    }else if([languageCode hasPrefix:@"en"]){
        languageCode = @"en";//英语
    }else{
        languageCode = @"zh-hans";
    }
    [ self.requestManager.requestSerializer setValue:languageCode forHTTPHeaderField:@"lang"];

    if ([method isEqualToString:@"POST"]) {
        [self.requestManager POST:urlString parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSData *saveData = responseObject;
            NSString *uniqueKey = [self uniqueKeyForUrlString:urlString
                                                       method:method
                                                       params:param];
            
            if (isCache) {
                [self.afCache setCacheData:saveData forKey:uniqueKey];
            }
            if (!responseObject) {
                responseObject = [[self.afCache cacheDataForKey:uniqueKey]copy];
            }
            
            success(task,responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error  %@",error);
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            
            if (responses.statusCode ==401 ||responses.statusCode ==400)
            {
//                 [kWindow makeToast:@"请重新登陆" duration:1.2 position:CSToastPositionCenter];
                [[NSNotificationCenter defaultCenter]postNotificationName:ExitLogonNotificationse object:nil];
                [EXUserManager removeUserInfo];
            }
            if (error.code) {
                
            }
            NSString *uniqueKey = [self uniqueKeyForUrlString:urlString
                                                       method:method
                                                       params:param];
            NSData *getData = [self.afCache cacheDataForKey:uniqueKey];
            if (getData) {
                success(task,getData);
            }else{
                [[AFNetworkReachabilityManager sharedManager] startMonitoring];
                [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
                    if (status == AFNetworkReachabilityStatusNotReachable ) {
//                        [TopAlertView SetUpbackgroundColor:[MAINCOLOR colorWithAlphaComponent:0.5] andStayTime:1 andImageName:@"set_bj" andTitleStr:@"请检测网络连接是否异常" andTitleColor:[UIColor whiteColor]];
                     
                     
                        return ;
                    }
                }];
                fail(task,error);
            }
        }];
        
    }else if ([method isEqualToString:@"GET"]){
        
        [self.requestManager GET:urlString parameters:param progress:^(NSProgress * _Nonnull downloadProgress)
        {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSData *saveData = responseObject;
            NSString *uniqueKey = [self uniqueKeyForUrlString:urlString
                                                       method:method
                                                       params:param];
            if (isCache) {
                [self.afCache setCacheData:saveData forKey:uniqueKey];
            }
            if (!responseObject) {
                responseObject = [[self.afCache cacheDataForKey:uniqueKey]copy];
            }
            
            success(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            NSLog(@"error  %@",error);
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
         
            if (responses.statusCode ==401 ||responses.statusCode ==400)
            {
//                [kWindow makeToast:@"请重新登陆" duration:1.2 position:CSToastPositionCenter];
                [[NSNotificationCenter defaultCenter]postNotificationName:ExitLogonNotificationse object:nil];
                [EXUserManager removeUserInfo];
            }

            NSString *uniqueKey = [self uniqueKeyForUrlString:urlString
                                                       method:method
                                                       params:param];
            NSData *getData = [self.afCache cacheDataForKey:uniqueKey];
            if (getData) {
                success(task,getData);
            }else{
                fail(task,error);
            }
        }];        
    }else if ([method isEqualToString:@"DELETE"]){
        [self addObserver:self forKeyPath:@"" options:NSKeyValueObservingOptionNew context:nil];
        [self.requestManager DELETE:urlString parameters:param success:success failure:fail];
    }

}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;

}
- (BOOL)checkURLNeedToken:(NSString *)urlString
{
    return !([urlString isEqualToString:@""]
             );
}
- (NSString *)uniqueKeyForUrlString:(NSString *)urlString
                             method:(NSString *)method
                             params:(NSDictionary *)params
{
    NSString *str = [NSString stringWithFormat:@"%@ %@",
                            method,
                            urlString];
    for (NSString *key in params){
        NSString *value = [NSString stringWithFormat:@"%@",params[key]];
        str = [str stringByAppendingString:value];
        str = [str stringByAppendingString:key];
    }
    return str;
}
- (NSString *)baseUrl;
{
    return self.baseUrlStr;
}
@end
